package org.springframework.boot.autoconfigure.datasource;

import org.springframework.beans.factory.annotation.Value;
import top.malaoshi.util.StringUtil;
import top.malaoshi.webmvc.ApplicationConfigFileReader;

import java.util.Map;
import java.util.Set;

public class AbstractDataSourceConfig {
//    @Value("${spring.datasource.url}")
//    protected String url;
//    @Value("${spring.datasource.driver-class-name}")
//    protected String driverClassName;
//    @Value("${spring.datasource.username}")
//    protected String username;
//    @Value("${spring.datasource.password}")
//    protected String password;

    /**
     * 将 application.yaml 或 application.yml 或 application.properties 的连接池其他配置放到map中
     * @param map
     * @param prefix 连接池其他配置的前缀，如：druid的前缀是：spring.datasource.druid
     */
    protected void putConfig(Map map,String prefix){
        map.put("url",ApplicationConfigFileReader.getValue("spring.datasource.url"));
        map.put("driverClassName",ApplicationConfigFileReader.getValue("spring.datasource.driver-class-name"));
        map.put("username",ApplicationConfigFileReader.getValue("spring.datasource.username"));
        map.put("password",ApplicationConfigFileReader.getValue("spring.datasource.password"));

        Set<Map.Entry<Object, Object>> entries = ApplicationConfigFileReader.getProperties().entrySet();
        for(Map.Entry<Object, Object> item : entries){
            String key = (String) item.getKey();
            if(key.startsWith(prefix)){
                String newKey = StringUtil.lastSlice(key,".",false);
                Object value = item.getValue();
                /*
                 DruidDataSource要求值为String类型
                 当读取yaml文件，当值为数字时，其类型是 Integer，需要转成String类型
                 */
                if(value == null || value instanceof String) {
                    map.put(newKey, value);
                }else{
                    map.put(newKey, String.valueOf(value));
                }
            }
        }
    }
}
